﻿#region Licence
// <copyright file="Database.POCO/BaseEntity.cs" company="Kopigi">
// Copyright © Kopigi 2014
// </copyright>
// ****************************************************************************
// <author>Marc PLESSIS</author>
// <date>10/10/2014</date>
// <project>Nentang.wpf</project>
// <web>http://nentang.codeplex.com</web>
// <license>
// The MIT License (MIT)
// 
// Copyright (c) 2013 Marc Plessis
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// 
// </license>
#endregion
#region using

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Windows;

#endregion

namespace Database.POCO.Base
{
    /// <summary>
    /// Classe de base des entitées de base de données
    /// </summary>
    public abstract class BaseEntity : EntityTemplates, IDisposable, IComparable<BaseEntity>, INotifyPropertyChanged, INotifyDataErrorInfo
    {

        /// <summary>
        /// Code utilisateur par défaut lors de l'enregistrement d'un élement
        /// </summary>
        private const string UserDefaultCode = "ADMIN";

        /// <summary>
        /// Primary Key
        /// </summary>
        /// <remarks>
        /// ID en majuscule correspond à la norme de Entity Framework Code First
        /// </remarks>
        public Int64 ID { get; set; }

        /// <summary>
        /// Code de l'utilisateur lors de l'enregistrement d'un élément
        /// </summary>
        public string SysCodeUtilisateurCreation { get; set; }

        /// <summary>
        /// Date de création de l'élément
        /// </summary>
        public DateTime SysDateCreation { get; set; }

        /// <summary>
        /// Code utilisateur lors de la modification de l'élément
        /// </summary>
        public string SysCodeUtilisateurModification { get; set; }

        /// <summary>
        /// Date de modification de l'élément
        /// </summary>
        public DateTime SysDateModification { get; set; }

        /// <summary>
        /// Identifiant unique de la ligne
        /// </summary>
        public Guid IdentifiantUnique { get; set; }

        #region cstor

        protected BaseEntity()
        {
            SysDateCreation = DateTime.Now;
            SysDateModification = DateTime.Now;
            IdentifiantUnique = Guid.NewGuid();
            SysCodeUtilisateurCreation = UserDefaultCode;
            SysCodeUtilisateurModification = UserDefaultCode;
            _validationResults = new List<ValidationResult>();
        }

        #endregion

        /// <summary>
        /// Dispose l'entité
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
        }

        /// <summary>
        /// Comparer 2 valeurs d'entités
        /// </summary>
        /// <param name="other"></param>
        /// <returns></returns>
        public int CompareTo(BaseEntity other)
        {
            return ID.CompareTo(other.ID);
        }

        #region clone

        /// <summary>
        /// Fais une copie de l'objet courant
        /// </summary>
        public BaseEntity Clone()
        {
            return (BaseEntity)this.MemberwiseClone();
        }

        #endregion

        #region protected

        protected virtual void Dispose(bool disposing)
        {
            GC.Collect();
        }

        #endregion

        #region OnPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpression)
        {
            var propertyName = GetPropertyName(propertyExpression);
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
            Validate();
        }

        protected string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
        {
            if (propertyExpression == null)
            {
                throw new ArgumentNullException("propertyExpression");
            }

            var body = propertyExpression.Body as MemberExpression;

            if (body == null)
            {
                throw new ArgumentException("Invalid argument", "propertyExpression");
            }

            var property = body.Member as PropertyInfo;

            if (property == null)
            {
                throw new ArgumentException("Argument is not a property", "propertyExpression");
            }

            return property.Name;
        }

        #endregion

        #region INotifyDataErrorInfo

        /// <summary>
        /// Indique si l'objet a bien passé les validations
        /// </summary>
        public bool IsValid
        {
            get
            {
                Validate();
                return !HasErrors;
            }
        }

        /// <summary>
        /// Validates a property of the object
        /// </summary>
        /// <param name="propertyName"></param>
        protected void Validate(string propertyName)
        {
            var value = GetPropertyValue(propertyName);
            RemoveErrorsForProperty(propertyName);
            Validator.TryValidateProperty(value,
                                          new ValidationContext(this, null, null)
                                          {
                                              MemberName = propertyName
                                          },
                                          _validationResults);
            RaiseErrorsChanged(propertyName);
        }

        /// <summary>
        /// Validates all properties of the object
        /// </summary>
        private void Validate()
        {
            _validationResults.Clear();
            Validator.TryValidateObject(this,
                                        new ValidationContext(this, null, null),
                                        _validationResults,
                                        true);

            foreach (var result in _validationResults)
            {
                RaiseErrorsChanged(result.MemberNames.First());
            }
        }

        /// <summary>
        /// Gets the value of a given property
        /// </summary>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        private object GetPropertyValue(string propertyName)
        {
            var type = GetType();

            var propertyInfo = type.GetProperty(propertyName);

            if (propertyInfo == null)
            {
                throw new ArgumentException(
                    string.Format("Couldn't find any property called {0} on type {1}",
                                  propertyName, type));
            }

            return propertyInfo.GetValue(this, null);
        }

        private readonly ICollection<ValidationResult> _validationResults;

        /// <summary>
        /// Gets the validation errors for a specified property or for the entire entity.
        /// </summary>
        /// <returns>
        /// The validation errors for the property or entity.
        /// </returns>
        /// <param name="propertyName">The name of the property to retrieve validation errors 
        /// for; or null or <see cref="F:System.String.Empty"/>, to retrieve 
        /// entity-level errors.</param>
        public IEnumerable GetErrors(string propertyName)
        {
            return _validationResults
                .Where(result => result.MemberNames.Contains(propertyName));
        }

        /// <summary>
        /// Gets a value that indicates whether the entity has validation errors. 
        /// </summary>
        /// <returns>
        /// true if the entity currently has validation errors; otherwise, false.
        /// </returns>
        public bool HasErrors
        {
            get { return _validationResults.Any(); }
        }

        public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

        private void RaiseErrorsChanged(string propertyName)
        {
            if (ErrorsChanged != null)
            {
                ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
            }
        }

        /// <summary>
        /// Clears the errors on a given property
        /// </summary>
        /// <param name="propertyName"></param>
        /// <param name="raiseError"> </param>
        protected void RemoveErrorsForProperty(string propertyName, bool raiseError = false)
        {
            var validationResults = _validationResults
                .Where(result => result.MemberNames.Contains(propertyName))
                .ToList();

            foreach (var result in validationResults)
            {
                _validationResults.Remove(result);
            }

            if (raiseError)
            {
                RaiseErrorsChanged(propertyName);
            }
        }

        /// <summary>
        /// Add an error to a given property
        /// </summary>
        /// <param name="propertyName"></param>
        /// <param name="errorMessage"></param>
        /// <param name="raiseError"> </param>
        protected void AddErrorForProperty(string propertyName, string errorMessage, bool raiseError = true)
        {
            if (_validationResults
                .Any(result => result.ErrorMessage.Contains(errorMessage)
                               && result.MemberNames.Contains(propertyName)))
            {
                return;
            }

            _validationResults.Add(new ValidationResult(errorMessage,
                                                        new List<string>
                                                            {
                                                                propertyName
                                                            }));
            if (raiseError)
            {
                RaiseErrorsChanged(propertyName);
            }
        }
        #endregion
    }
}
